﻿(function () {
    function ReadyToRun() {
        var token = $jq('script[token]').attr("token");
        var scriptName = "RecorderGen3";
        var destinationUrl = 'http://imaginarydevelopment.com/Sfc/Recorder/Save';
        //window.alert('bookmarklet started');
        String.prototype.trim = function () {
            /* /^\s+|\s+$/g,'' */
            return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '').replace(/[\r\n\s]+|\s\s+|\s*\&nbsp\s*/g, ' ');
        };
        function ProcessPlanet(planets, index, tr) {
            planets.push('planet' + index);
        }
        function ToJson(data) {

            if (typeof (JSON) != 'undefined' && typeof (JSON.stringify) != 'undefined')
                return JSON.stringify(data);

            if (typeof (JSON2) != 'undefined' && typeof (JSON2.stringify) != 'undefined')
                return JSON2.stringify(data);
            if (data.toJSON)
                return data.toJSON();
            throw "Could not find Json";
        }
        function ProcessGalaxy() {
            var isStandard = ($jq('title').text().match(/extreme/i) === null);
            var galaxy = $jq('input#galaxy').val();
            var system = $jq('input#solar_system').val();
            var planetInfo = new Array();

            $jq('table#planets.planets tr.planet').each(function (index, tr) {
                var slot = $jq('td.slot', tr).text();
                var player = $jq('td.player span:first', tr).text().trim();
                var symbols = $jq('td.player span:first span.symbols', tr);
                var status = '';
                if (symbols)
                    status = symbols.text();

                planetInfo[index] = galaxy.trim() + ':' + system.trim() + ':' + slot + "," + player + ',' + status +
             ',' + $jq('td.alliance span a', tr).text().trim();
            });
            /*alert('data will be:'+planetInfo);*/
            var postData = { 'Planets': planetInfo, 'Token': token, 'IsStandard': isStandard };

            var jsonData = ToJson(postData);

            //var methodCallString = Object.toJSON ? Object.toJSON(options.jsonMethodCall) : JSON.stringify(options.jsonMethodCall);
            destination.data = jsonData

            $jq.ajax(destination);
            //invocation.send('test');
            //}
        }

        function AjaxSuccess(data, textStatus, xmlHttpRequest) {
            if (typeof (data) == 'undefined') {
                return alert('Data is undefined');
            }
            alert(data || 'ajax success, data may not have saved');
        }
        function AjaxError(xmlHttpRequest, textStatus, errorThrown) {
            alert('ajax failure:' + textStatus);
        }
        var destination = { url: destinationUrl, type: 'POST', success: AjaxSuccess, error: AjaxError,
            contentType: 'text/plain'
        };


        if ($jq('body').length <= 0) {
            return alert('Could not query body length');
        }
        if ($jq('head title:contains(BookmarkletTest)').length > 0) {
            alert('doing test');
            destination.data = { data: 'BookmarkletTestAjax' };
            $jq.ajax(destination);
            return;
        }
        var primary = $jq('div.primary a.selected').text();
        switch (primary) {
            case 'Galaxy':
                ProcessGalaxy();
                break;
            case 'Fleets':
                destination.data = { data: 'Fleet Screen' };
                $jq.ajax(destination);
                break;
            default:
                destination.data = { data: 'No Script for this page' };
                $jq.ajax(destination);
                alert('No script for this page');
        }
    }

    var el = document.createElement('div'), b = document.getElementsByTagName('body')[0]; otherlib = false, msg = ''; el.style.position = 'fixed'; el.style.height = '32px'; el.style.width = '220px'; el.style.marginLeft = '-110px'; el.style.top = '0'; el.style.left = '50%'; el.style.padding = '5px 10px 5px 10px'; el.style.zIndex = 1001; el.style.fontSize = '12px'; el.style.color = '#222'; el.style.backgroundColor = '#f99'; if (typeof jQuery != 'undefined') { msg = 'This page already using jQuery v' + jQuery.fn.jquery; return showMsg(); } else if (typeof $ == 'function') { otherlib = true; } function getScript(url, success) { var script = document.createElement('script'); script.src = url; var head = document.getElementsByTagName('head')[0], done = false; script.onload = script.onreadystatechange = function () { if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { done = true; success(); } }; head.appendChild(script); } getScript('http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', function () {
        if (typeof jQuery == 'undefined') { msg = 'Sorry, but jQuery wasn\'t able to load'; } else {

            msg = 'This page is now jQuerified with v' + jQuery.fn.jquery; if (otherlib) { msg += ' and noConflict(). Use $jq(), not $().'; }

            /* Begin jQuerify+Json */
            if (typeof (jQuery) == 'undefined') {
                return alert('jQuery not defined');
            }

            if (typeof ($jq) == 'undefined') {
                if (typeof ($) != 'undefined') {
                    $jq = $;
                } else {
                    return alert('$jq->jquerify not defined');
                }
            }
            if (typeof (JSON) == 'undefined' && typeof (JSON2) == 'undefined') {
                getScript('http://imaginarydevelopment.com/Sfc/Scripts/ClientScripts/json2.js', ReadyToRun);
            }
            else {
                ReadyToRun();
            }
            /* End jQuerify+Json */
        } return showMsg();
    }); function showMsg() { el.innerHTML = msg; b.appendChild(el); window.setTimeout(function () { if (typeof jQuery == 'undefined') { b.removeChild(el); } else { jQuery(el).fadeOut('slow', function () { jQuery(this).remove(); }); if (otherlib) { $jq = jQuery.noConflict(); } } }, 2500); }
})();

